'''
Created on Mar 3, 2011

@author: oabalbin
'''
import logging
#import argparse
import os
import sys

from optparse import OptionParser
from job_runner import qsub_cac, qsub_loc, run_local
from config import ExomePipelineConfig, ExomeAnalysisConfig
import run_lane
from bam_cleaner import bam_cleaner_samples
from run_variantCalls import main_variantCalls
import exome.gatk_cluster.reads_realignment_job as rra
import exome.snps_callers.snps_byGatk as gtk
import exome.snps_callers.snps_bySamTools3 as sst


def run_analysis(analysis_file, config_file, num_processors, runfunc):
    #
    # Read configuration
    #
    config = ExomePipelineConfig()
    config.from_xml(config_file)
    analysis = ExomeAnalysisConfig()
    analysis.from_xml(analysis_file, config.output_dir)
    
    for run_name, run in config.run_param.iteritems():
        # Run parameters        
        do_recalibration, quick_dirty, do_paired_samples, multi_samples = \
        run.do_recal, run.quick_dirty, run.paired_samples, run.multi_samples

        # Main loop for all samples
        for sample in analysis.samples:
            # Create sample directory
            if not os.path.exists(sample.output_dir):
                logging.info("Created sample dir %s" % (sample.output_dir))
                os.makedirs(sample.output_dir)
            #
            # Process lanes
            #
            lane_deps = []
            for lane in sample.lanes:
                logging.info("Processing lane %s" % (lane.name))
                # write lane configuration to a separate XML file
                xmlstring = lane.to_xml()
                lane_file = os.path.join(sample.output_dir, lane.name + ".xml")
                f = open(lane_file, "w")
                print >>f, xmlstring
                f.close()
                # run lane job
                # lane job: 
                # If there not aligned bam file ready
                thlane_deps=run_lane.run_job(lane_file, analysis.lane_dir, config_file, num_processors, runfunc)
                # else:
                # take a preexistent bam file and: i)Create a temporary exon target bam file 
                # ii) create a smaller bam file with actionable genes only
                # lunch to parallel analyis. i) the full exome, ii) only actionable genes 
                lane_deps.extend(thlane_deps)
                                    
                #pass
        
        # Call Variants Step
        gtk_deps, sst_deps = main_variantCalls(run,lane_deps,\
                      analysis, config, num_processors, runfunc, lane_deps)
        
        # General evaluation step
        
        # Variant Annotation Step
        
        pass



def main():
    logging.basicConfig(level=logging.DEBUG,
                        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    
    optionparser = OptionParser("usage: %prog [options] ")
    
    optionparser.add_option("-r", "--config_file", dest="config_file",
                            help="file with run configuration")
    optionparser.add_option("-a", "--analysis_file", dest="analysis_file",
                            help="file with experiment configuration") 
    optionparser.add_option("--quality_recal", dest="quality_recal", action="store_true", default=False,
                            help="Performs base quality recalibration") 
    optionparser.add_option("--paired_samples", dest="paired_samples", action="store_true", default=False,
                            help="paired samples snv calling, default multisamples") 
    '''
    optionparser.add_option("--multi_samples", dest="multi_samples", action="store_true", default=False,
                            help="multi-sample snv calling, default paired samples")  
    '''
    optionparser.add_option("--local", dest="local", action="store_true", default=False)
    optionparser.add_option("--cluster", dest="cluster", action="store_true", default=False)
    optionparser.add_option("-p", "--processes", type=int, dest="num_processors", default=1)
    
    
    (options, args) = optionparser.parse_args()
    
    #analysis_file, config_file = args[0], args[1]
     
        
    if not (options.local ^ options.cluster):
        optionparser.error("Must set either --local or --cluster to run job")
    if options.local:
        jobrunfunc = run_local
    elif options.cluster:
        jobrunfunc = qsub
    #run_analysis(options.analysis_file, options.config_file, options.num_processors, jobrunfunc)
    run_analysis(options.analysis_file, options.config_file, options.num_processors, jobrunfunc)

if __name__ == '__main__': main()